package jast.util.es;

import jast.util.Config;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ESClient管理类
 */
@Slf4j
public class ElasticSearchClientManager {

    static volatile TransportClient client = null;



    /**
     * 获取ES Client
     *
     * @return
     */
    public static TransportClient getESClient() {

            if (client == null) {
                System.setProperty("es.set.netty.runtime.available.processors", "false");
                Settings settings = Settings.builder()
//                    .put("cluster.name", "cluster1")
                        .put("cluster.name", "bjga-gz") //测试环境
                        //可以设置client.transport.sniff为true来使客户端去嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中，
                        // 这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端，它会自动帮你添加，并且自动发现新加入集群的机器
                        .put("client.transport.sniff", true)
                        .build();

                client = new PreBuiltTransportClient(settings);
                try {
//                client.addTransportAddress(
//                        new TransportAddress(InetAddress.getByName("Mac.local"), 9300))
//                client.addTransportAddress(
//                                new TransportAddress(InetAddress.getByName("10.8.10.12"), 9300))//测试环境
//                .addTransportAddress(
//                        new TransportAddress(InetAddress.getByName("10.8.10.13"), 9300))//测试环境
//                .addTransportAddress(
//                        new TransportAddress(InetAddress.getByName("10.8.10.14"), 9300))//测试环境
//                ;

                    String ips = Config.IP;
                    for (String ServerIp : ips.split(",")) {
                        String[] split = ServerIp.split(":");
                        String ip = split[0];
                        Integer port = Integer.parseInt(split[1]);
                        client.addTransportAddress(
                                new TransportAddress(InetAddress.getByName(ip), port));
                    }
                    log.info("调用ES IP为:{}", ips);

                    //                client.addTransportAddress(
//                        new TransportAddress(InetAddress.getByName("172.16.99.16"), 9300))//测试环境
//;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }


        }

        return client;
    }

    /**
     * 关闭ES Client
     */
    public static void closeESClient() {
        client.close();
    }
}
